package top.lingkang.finaloauth2.server.client;

import top.lingkang.finaloauth2.server.error.ServerException;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lingkang
 * Created by 2022/3/24
 */
public class ClientDetailsServiceBuilder {
    private HashMap<String, ClientDetails> memory;
    private DataSource dataSource;

    private String tempClientId;
    private ClientDetails tempClient;

    public ClientDetailsServiceBuilder inMemory() {
        memory = new HashMap<>();
        return this;
    }

    public void useJdbc(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public ClientDetailsServiceBuilder addClient(String clientId) {
        if (memory == null) {
            throw new ServerException("请先添加 inMemory");
        }
        this.tempClientId = clientId;
        tempClient = new ClientDetails();
        tempClient.setClientId(clientId);
        memory.put(clientId, tempClient);
        return this;
    }

    public ClientDetailsServiceBuilder secret(String secret) {
        if (tempClientId == null) {
            throw new ServerException("请先添加 clientId : addClient");
        }
        ClientDetails clientDetails = memory.get(tempClientId);
        clientDetails.setClientSecret(secret);
        memory.put(tempClientId, clientDetails);
        return this;
    }

    public ClientDetailsServiceBuilder authorizedGrantTypes(String... type) {
        if (tempClientId == null) {
            throw new ServerException("请先添加 clientId : addClient");
        }
        ClientDetails clientDetails = memory.get(tempClientId);
        Set<String> grantType = clientDetails.getGrantType();
        if (grantType == null) {
            grantType = new HashSet<>(Arrays.asList(type));
        } else {
            grantType.addAll(new HashSet<>(Arrays.asList(type)));
        }

        clientDetails.setGrantType(grantType);
        memory.put(tempClientId, clientDetails);
        return this;
    }

    public ClientDetailsServiceBuilder scope(String scope) {
        if (tempClientId == null) {
            throw new ServerException("请先添加 clientId : addClient");
        }
        ClientDetails clientDetails = memory.get(tempClientId);
        clientDetails.setScope(scope);
        memory.put(tempClientId, clientDetails);
        return this;
    }

    public HashMap<String, ClientDetails> getMemory() {
        return memory;
    }

    public DataSource getDataSource() {
        return dataSource;
    }
}
